package com.nbsaas.boot.jobs;

import com.nbsaas.boot.quartz.api.apis.SchedulingTaskApi;
import com.nbsaas.boot.quartz.api.apis.SchedulingTaskRecordApi;
import com.nbsaas.boot.quartz.api.domain.request.SchedulingTaskRecordRequest;
import com.nbsaas.boot.quartz.api.domain.response.SchedulingTaskResponse;
import com.nbsaas.boot.quartz.ext.domain.request.DataValue;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.utils.ObjectUtils;
import jodd.http.HttpRequest;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Date;
import java.util.List;
import java.util.Map;


public class HttpJob implements Job {

    private final Logger logger = LoggerFactory.getLogger("HttpJob");

    public void execute(JobExecutionContext context) {
        JobDataMap map = context.getJobDetail().getJobDataMap();


        Object applicationContext = map.get("applicationContext");
        if (applicationContext == null) {
            return;
        }

        if (applicationContext instanceof ApplicationContext) {
            ApplicationContext beans = (ApplicationContext) applicationContext;
            SchedulingTaskRecordApi recordApi = beans.getBean(SchedulingTaskRecordApi.class);

            SchedulingTaskApi scheduleTaskApi = beans.getBean(SchedulingTaskApi.class);

            Long id = map.getLong("id");

            SchedulingTaskResponse task = scheduleTaskApi.oneData(Filter.eq("id", id));
            if (task == null) {
                return;
            }
            String url = map.getString("url");
            logger.info("url:{}", url);
            logger.info("time:{}", new Date());
            int state = 1;
            String body = "";
            if (url != null) {
                try {
                    HttpRequest httpRequest;

                    if ("POST".equals(task.getRequestMethod())) {
                        httpRequest = HttpRequest.post(url);
                        httpRequest.charset("utf-8");
                        if ("application/json".equals(task.getContentType())) {
                            httpRequest.contentType("application/json");
                            httpRequest.bodyText(task.getRequestBody(), "application/json", "utf-8");
                        }
                        if ("application/x-www-form-urlencoded".equals(task.getContentType())) {
                            //DataValue
                            List<DataValue> dataList = ObjectUtils.getList(DataValue.class, task.getRequestBody());
                            if (dataList != null) {
                                for (DataValue dataValue : dataList) {
                                    httpRequest.form(dataValue.getKey(), dataValue.getValue());
                                }
                            }
                        }
                    } else {
                        httpRequest = HttpRequest.get(url);
                    }
                    if (task.getRequestHeader() != null) {
                        Map<String, String> dataList = ObjectUtils.getObject(Map.class, task.getRequestHeader());
                        if (dataList != null) {
                            for (String key : dataList.keySet()) {
                                httpRequest.header(key, dataList.get(key));
                            }
                        }
                    }
                    String bodyTxt = httpRequest.send().charset("utf-8").bodyText();
                    logger.info(bodyTxt);
                    logger.info("执行完成");
                    body = "ok";
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("执行失败");
                    body = e.getMessage();
                    state = 2;
                }
            } else {
                logger.info("url为空");
            }


            if (task.getRecordType() == null) {
                task.setRecordType(1);
            }
            if (task.getRecordType() == 2) {
                return;
            }

            SchedulingTaskRecordRequest form = new SchedulingTaskRecordRequest();
            form.setSchedulingTask(id);
            form.setState(state);
            form.setNote(body);
            recordApi.create(form);

        }

    }

}
